<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { StorageManager } from '@vben-core/shared/cache';

import {
  ElButton,
  ElCheckTag,
  ElDivider,
  ElMessage,
  ElMessageBox,
  ElPagination,
  ElPopover,
  ElRow,
  ElTable,
  ElTableColumn,
} from 'element-plus';

import { fileApi, messageApi } from '#/api';
import { $t } from '#/locales';
import { useWebSocketStore } from '#/store';

import { FileViewer } from './components';

const websocketStore = useWebSocketStore();
const currentPage = ref(1);
const pageSize = ref(10);
const parentBorder = ref(true);
const tableData = ref([] as any);
const totalPage = ref(0 as number);
const selectedMsgs = ref([] as any);
const isFileViewerShow = ref(false);
const currentMsg = ref({} as any);
const isLoading = ref(false);
const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
const handleSizeChange = (_val: number) => {};
const flushMsgList = async (page: number) => {
  try {
    isLoading.value = true;
    const data = await messageApi.getAllMsg(
      storageManager.getItem('email') as string,
      page,
    );
    if (data) {
      setTimeout(() => {
        isLoading.value = false;
        tableData.value = data.msgs;
        totalPage.value = data.count;
      }, 300);
    }
  } catch (error) {
    console.error(error);
  }
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  flushMsgList(val);
};
const readAll = () => {
  messageApi
    .getNoSentMessage(storageManager.getItem('email') as string)
    .then((res) => {
      if (res) {
        const msgIdArr = res.data.map((msg: any) => msg.id);
        messageApi.readMsgs({ msgIds: msgIdArr }).then((res) => {
          if (res) {
            websocketStore.updateMsgQueue();
            flushMsgList(currentPage.value);
          } else {
            ElMessage.error('已读失败！');
          }
        });
      }
    });
};

const readMsg = (id: string) => {
  messageApi.readAMsg(id).then((res) => {
    if (res.code === '200') {
      websocketStore.updateMsgQueue();
      flushMsgList(currentPage.value);
    } else {
      ElMessage.error('已读失败！');
    }
  });
};
const handleSelectionChange = (val: any) => {
  selectedMsgs.value = val.map((msg: any) => msg.id);
};
const deleteMsgs = () => {
  messageApi.deleteMsgs(selectedMsgs.value).then((res) => {
    if (res.code === '200') {
      flushMsgList(currentPage.value);
    } else {
      ElMessage.error('删除失败！');
    }
  });
};
const readMsgs = () => {
  messageApi.readMsgs({ msgIds: selectedMsgs.value }).then((res) => {
    if (res.code === '200') {
      websocketStore.updateMsgQueue();
      flushMsgList(currentPage.value);
    } else {
      ElMessage.error('已读失败！');
    }
  });
};
const openFileViewerDialog = () => {
  isFileViewerShow.value = true;
};
const importResource = (msg: any) => {
  const resourceId = msg.resource;
  currentMsg.value = msg;
  ElMessageBox.confirm(
    `是否将该资源${resourceId}导入您的个人空间？`,
    '导入资源',
    {
      confirmButtonText: '导入',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      openFileViewerDialog();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Import canceled',
      });
    });
};
const handleCloseFileViewerDialog = () => {
  isFileViewerShow.value = false;
};
const handleConfirmFileViewerDialog = (catalogId: string) => {
  fileApi
    .importFile({ fileId: currentMsg.value.resource, catalogId })
    .then((res) => {
      if (res) {
        readMsg(currentMsg.value.id);
        ElMessage.success(res.message);
      }
    });
};

onMounted(() => {
  flushMsgList(currentPage.value);
});
</script>

<template>
  <div>
    <div class="all">
      <div class="msgBoxContainer shadowRow">
        <h2>{{ $t('page.messageList.title') }}</h2>
        <ElDivider style="margin: 5px" border-style="hidden" />
        <ElRow class="btn">
          <ElButton type="warning" round @click="readAll">
            {{ $t('page.messageList.readAll') }}
          </ElButton>
          <ElButton
            v-if="selectedMsgs.length > 0"
            type="warning"
            @click="readMsgs"
            round
          >
            {{ $t('page.messageList.readSelected') }}
          </ElButton>
          <ElButton
            v-if="selectedMsgs.length > 0"
            type="danger"
            @click="deleteMsgs"
            round
          >
            {{ $t('page.messageList.deleteSelected') }}
          </ElButton>
        </ElRow>
        <ElDivider style="margin: 5px" border-style="hidden" />
        <ElTable
          max-height="349"
          :data="tableData"
          :border="parentBorder"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="isLoading"
        >
          <ElTableColumn align="center" type="selection" width="35" />
          <ElTableColumn align="center" type="expand">
            <template #default="props">
              <div class="msgContent">
                <div class="msgRow">
                  <h4>{{ $t('page.messageList.topic') }}:</h4>
                  &nbsp;&nbsp;
                  <p m="t-0 b-2">{{ props.row.topic }}</p>
                </div>
                <div class="msgRow">
                  <h4>{{ $t('page.messageList.from') }}:</h4>
                  &nbsp;&nbsp;
                  <p m="t-0 b-2">{{ props.row.from }}</p>
                </div>
                <div class="msgRow">
                  <h4>{{ $t('page.messageList.to') }}:</h4>
                  &nbsp;&nbsp;
                  <p m="t-0 b-2">{{ props.row.to }}</p>
                </div>
                <div class="msgRow">
                  <h4>{{ $t('page.messageList.content') }}:</h4>
                  &nbsp;&nbsp;
                  <p m="t-0 b-2">{{ props.row.text }}</p>
                </div>
                <div class="msgRow">
                  <h4>{{ $t('page.messageList.fileAttachment') }}:</h4>
                  &nbsp;&nbsp;
                  <ElCheckTag
                    size="small"
                    checked
                    class="ml-2"
                    @change="importResource(props.row)"
                  >
                    {{ props.row.resource }}
                  </ElCheckTag>
                </div>
                <div class="msgRow">
                  <h4>{{ $t('page.messageList.topic') }}:</h4>
                  &nbsp;&nbsp;
                  <div v-if="props.row.isRead">
                    <span class="readMsg">{{
                      $t('page.messageList.read')
                    }}</span>
                  </div>
                  <div v-else>
                    <ElPopover
                      placement="top-start"
                      width="155"
                      trigger="hover"
                      content="将此条消息标为已读"
                    >
                      <template #reference>
                        <ElButton @click="readMsg(props.row.id)">
                          未读
                        </ElButton>
                      </template>
                    </ElPopover>
                  </div>
                </div>
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn
            align="center"
            :label="$t('page.messageList.topic')"
            prop="topic"
          />
          <ElTableColumn
            align="center"
            :label="$t('page.messageList.content')"
            prop="text"
          />
          <ElTableColumn
            align="center"
            :label="$t('page.messageList.time')"
            prop="date"
          />
          <ElTableColumn align="center" :label="$t('page.messageList.status')">
            <template #default="scope">
              <div v-if="scope.row.isRead">
                <span class="readMsg">{{ $t('page.messageList.read') }}</span>
              </div>
              <div v-else>
                <ElPopover
                  placement="top-start"
                  width="155"
                  trigger="hover"
                  content="$t('page.messageList.unread')"
                >
                  <template #reference>
                    <ElButton @click="readMsg(scope.row.id)">
                      {{ $t('page.messageList.unread') }}
                    </ElButton>
                  </template>
                </ElPopover>
              </div>
            </template>
          </ElTableColumn>
        </ElTable>
        <ElDivider border-style="hidden" />
        <div class="demo-pagination-block">
          <ElPagination
            :current-page="currentPage"
            :page-size="pageSize"
            :background="false"
            layout="prev, pager, next, jumper"
            :total="totalPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <FileViewer
      v-if="isFileViewerShow"
      :is-file-viewer-show="isFileViewerShow"
      :data-name="$t('page.messageList.fileViewer.title')"
      @close-file-viewer="handleCloseFileViewerDialog"
      @confirm-select-folder="handleConfirmFileViewerDialog"
    />
  </div>
</template>

<style scoped>
.btn {
  display: flex;
  flex-direction: row;
  align-self: flex-end;
}

.msgBoxContainer {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 60vh;
  padding: 20px 60px;
  margin: 100px 200px;
  background-color: rgb(255 255 255);
  border-radius: 5px;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #9fb6cd;
}

.msgContent {
  padding: 5px 80px;
  border: 1px solid;
}

.shadowRow {
  box-shadow: 0 0 10px rgb(0 0 0 / 20%);
}

.readMsg {
  font-size: 13px;
  font-style: italic;
  color: #a1a1a1;
}

.noReadMsg {
  font-size: 13px;
  font-weight: bold;
  color: #020202;
}

:deep(.el-popover.el-popper) {
  text-align: center;
}

.msgRow {
  display: flex;
  align-items: center;
  height: 30px;
}
</style>
